package com.yulebaby.callsenter.ui.activity;


import android.app.Dialog;
import android.content.Intent;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.orhanobut.logger.Logger;
import com.yulebaby.callsenter.R;
import com.yulebaby.callsenter.adapter.CustomerAdapter;
import com.yulebaby.callsenter.adapter.CustomerInSeaAdapter;
import com.yulebaby.callsenter.bean.CustomerBean;
import com.yulebaby.callsenter.bean.ResultBean;
import com.yulebaby.callsenter.event.EventFactory;
import com.yulebaby.callsenter.event.RefreshEvent;
import com.yulebaby.callsenter.global.Constant;
import com.yulebaby.callsenter.http.HttpHelper;
import com.yulebaby.callsenter.http.callback.HttpCallback;
import com.yulebaby.callsenter.http.callback.ResultCallback;
import com.yulebaby.callsenter.task.RequestCustomerTask;
import com.yulebaby.callsenter.task.UploadCustomerTask;
import com.yulebaby.callsenter.ui.base.BaseActivity;
import com.yulebaby.callsenter.ui.view.CallDialog;
import com.yulebaby.callsenter.ui.view.CustomPopwindow;
import com.yulebaby.callsenter.ui.view.RobCustomerDialog;
import com.yulebaby.callsenter.ui.view.YuLeBaByLinearLayoutManager;
import com.yulebaby.callsenter.utils.CheckPhoneNumUtil;
import com.yulebaby.callsenter.utils.ComLogUtils;
import com.yulebaby.callsenter.utils.CommonUtil;
import com.yulebaby.callsenter.utils.KeyBoardUtils;
import com.yulebaby.callsenter.utils.PhoneUtil;
import com.yulebaby.callsenter.utils.ThreadUtils;
import com.yulebaby.callsenter.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author: Zhangbo
 * Time: 2016年11月26日
 */
public class CustomerSearchActivity extends BaseActivity implements TextView.OnEditorActionListener, BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.iv_searchback)
    ImageView mIvSearchback;
    @BindView(R.id.et_searchnum)
    EditText mEtSearchnum;
    @BindView(R.id.tv_search)
    TextView mTvSearch;
    @BindView(R.id.tb_searchtitle)
    Toolbar mTbSearchtitle;
    @BindView(R.id.main_appbar)
    AppBarLayout mMainAppbar;
    @BindView(R.id.pb_showProgress)
    ProgressBar mPbShowProgress;
    @BindView(R.id.tv_showresult)
    TextView mTvShowresult;
    @BindView(R.id.ll_showsearchresult)
    LinearLayout mLlShowsearchresult;
    @BindView(R.id.rv_showsearch)
    RecyclerView mRvShowsearch;

    private ArrayList<CustomerBean> mCustomerlist, mCustomerInSealist;
    private CustomerAdapter mAdapter;
    private CustomerInSeaAdapter seaAdapter;
    private ArrayList<String> phoneNumList;
    private CustomerBean mCustomerBean;
    private CallDialog mCallDialog;
    private CustomPopwindow mCustomPopwindow;
    private RobCustomerDialog mRobDialogSuccess;
    private RobCustomerDialog mRobDialogFail;
    private boolean isCustomerFragment;

    private int datanum = 0;

    /**
     * 是否是加载更多
     */
    private boolean isLoadMore = false;

    @Override
    protected int initLayoutId() {
        return R.layout.activity_customer_search;
    }

    @Override
    protected void initView() {
        initToolBar(mTbSearchtitle, false, "");
//        initStatusBar();
        initShow();
        mEtSearchnum.setOnEditorActionListener(this);
        KeyBoardUtils.openKeybord(this, mEtSearchnum);
    }

    private void initShow() {
        mPbShowProgress.setVisibility(View.INVISIBLE);
        mTvShowresult.setVisibility(View.VISIBLE);
        mLlShowsearchresult.setVisibility(View.INVISIBLE);
        mRvShowsearch.setVisibility(View.INVISIBLE);
        //对搜索按钮进行动态设置
        mTvSearch.setTextColor(CommonUtil.getColor(R.color.seach_text_enable));
        mTvSearch.setClickable(true);

    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        isCustomerFragment = intent.getBooleanExtra(Constant.CLASS_NAME, true);
        mCustomerlist = new ArrayList<>();
        mCustomerInSealist = new ArrayList<>();
        phoneNumList = new ArrayList<>();
        mRvShowsearch.setHasFixedSize(true);
        mRvShowsearch.setLayoutManager(new YuLeBaByLinearLayoutManager(this));
        if (isCustomerFragment) {
            initCustomerData();
        } else {
            initWaterData();
        }
    }

    private void initWaterData() {
        seaAdapter = new CustomerInSeaAdapter(mCustomerInSealist);
        seaAdapter.setOnLoadMoreListener(this);
        seaAdapter.setEnableLoadMore(true);

        mRvShowsearch.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                //使用Intent的方式  使用消息总线的方式改进  粗糙版本
                Intent intent = new Intent(CustomerSearchActivity.this, CustomerInfoActivity.class);
                intent.putExtra(Constant.CUSTOMER_BEAN, (CustomerBean) baseQuickAdapter.getItem(position));
                intent.putExtra(Constant.IS_MODIFY, false);
                startActivity(intent);
                finish();
            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                mCustomerBean = (CustomerBean) baseQuickAdapter.getItem(position);
                switch (view.getId()) {
                    case R.id.iv_robcustomer:
                        robCustomers(view, mCustomerBean, position);
                        break;
                    case R.id.tv_looktrack:
                        if (mCustomerBean != null) {
                            initCustomPopwindow(view);
                        }
                        break;
                }
            }
        });
        mRvShowsearch.setAdapter(seaAdapter);
    }

    /**
     * 抢客户
     *
     * @param view
     * @param customer
     * @param position
     */
    private void robCustomers(View view, final CustomerBean customer, final int position) {
        UploadCustomerTask.doRobCustomer(CustomerSearchActivity.this, customer.getCustomer_id(), new HttpCallback<ResultBean>() {
            @Override
            public void onSuccessResultNull() {
                mRobDialogSuccess = new RobCustomerDialog(CustomerSearchActivity.this, true, new RobCustomerDialog.DialogCallBack() {
                    @Override
                    public void onConfirm(Dialog dialog) {
                        customer.setIsRobInSea(1);
                        seaAdapter.notifyItemChanged(position);
                        dialog.dismiss();
                        Intent addintent = new Intent(CustomerSearchActivity.this, AddPreSaleRemarkActivity.class);
                        addintent.putExtra(Constant.CUSTOMER_BEAN, customer);
                        startActivity(addintent);
                    }

                    @Override
                    public void onCancel(Dialog dialog) {
                        customer.setIsRobInSea(1);
                        seaAdapter.notifyItemChanged(position);
                        dialog.dismiss();
                    }
                });
                mRobDialogSuccess.show();
                EventBus.getDefault().post(EventFactory.CreateRefreshEvent(RefreshEvent.refreshDataFromInternet));
            }

            @Override
            public void onFailParam(String info) {
                super.onFailParam(info);
                mRobDialogFail = new RobCustomerDialog(CustomerSearchActivity.this, false, new RobCustomerDialog.DialogCallBack() {
                    @Override
                    public void onConfirm(Dialog dialog) {
                        customer.setIsRobInSea(1);
                        seaAdapter.notifyItemChanged(position);
                        dialog.dismiss();
                    }

                    @Override
                    public void onCancel(Dialog dialog) {
                    }
                });
                mRobDialogFail.show();
            }
        });
    }

    /**
     *
     */
    public void initCustomerData() {
        mAdapter = new CustomerAdapter(mCustomerlist);
        mRvShowsearch.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                //使用Intent的方式  使用消息总线的方式改进  粗糙版本
                Intent intent = new Intent(CustomerSearchActivity.this, CustomerInfoActivity.class);
                intent.putExtra(Constant.CUSTOMER_BEAN, (CustomerBean) baseQuickAdapter.getItem(position));
                intent.putExtra(Constant.IS_MODIFY, true);
                startActivity(intent);
                finish();
            }

            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                mCustomerBean = (CustomerBean) baseQuickAdapter.getItem(position);
                switch (view.getId()) {
                    case R.id.iv_robcustomer:
                        //选择前清空一下集合
                        phoneNumList.clear();
                        checkHasPhoneNum(mCustomerBean);
                        switchCallNum();
                        break;

                    case R.id.tv_addtrack://添加售前跟踪
                        Intent addintent = new Intent(CustomerSearchActivity.this, AddPreSaleRemarkActivity.class);
                        addintent.putExtra(Constant.CUSTOMER_BEAN, mCustomerBean);
                        startActivity(addintent);
                        break;

                    case R.id.tv_looktrack://查看跟踪记录
                        if (mCustomerBean != null) {
                            initCustomPopwindow(view);
                        }
                        break;
                }
            }
        });
        mRvShowsearch.setAdapter(mAdapter);
    }

    /**
     * 初始化Popwindow
     *
     * @param view
     */
    private void initCustomPopwindow(View view) {
        mCustomPopwindow = new CustomPopwindow(this, itemsOnClick, mCustomerBean);
        mCustomPopwindow.showAtLocation(view,
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    //为弹出窗口内部实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            mCustomPopwindow.backgroundAlpha(CustomerSearchActivity.this, 1f);
            switch (v.getId()) {
                case R.id.ib_cancal:
                    if (mCustomPopwindow != null && mCustomPopwindow.isShowing()) {
                        mCustomPopwindow.dismiss();
                    }
                    break;
            }
        }
    };

    /**
     * 选择想要拨打的电话号码
     */
    private void switchCallNum() {
        if (phoneNumList.size() == 1) {
            PhoneUtil.callPhones(phoneNumList.get(0));
        } else {
            mCallDialog = new CallDialog(this, phoneNumList, mCustomerBean);
            mCallDialog.setNumListener(num -> {
                PhoneUtil.callPhones(num);
                finish();
            });
            mCallDialog.show();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (KeyBoardUtils.getKeybordState(this)) {
            KeyBoardUtils.closeKeybord(this, mEtSearchnum);
        }
    }

    /**
     * 检查是否包含备用号码
     *
     * @param customerBean
     */
    private void checkHasPhoneNum(CustomerBean customerBean) {
        String phone = customerBean.getPhone();
        String spare_phone1 = customerBean.getSpare_phone1();
        String spare_phone2 = customerBean.getSpare_phone2();
        phoneNumList.add(phone);

        if (!TextUtils.isEmpty(spare_phone1)) {
            phoneNumList.add(spare_phone1);
        }
        if (!TextUtils.isEmpty(spare_phone2)) {
            phoneNumList.add(spare_phone2);
        }
    }

    private void initStatusBar() {
        mTbSearchtitle.setFitsSystemWindows(true);
        mTbSearchtitle.setClipToPadding(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        HttpHelper.getInstance().cancel(this);
        if (mCallDialog != null) {
            mCallDialog.dismiss();
        }
    }

    @OnClick({R.id.iv_searchback, R.id.tv_search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_searchback:
                finish();
                break;
            case R.id.tv_search:
                if (isCustomerFragment) {
                    mCustomerlist.clear();
                } else {
                    mCustomerInSealist.clear();
                }
                searchCustomerByPhone();
                break;
        }
    }

    /**
     * 通过电话号码寻找客户
     */
    private void searchCustomerByPhone() {
        if (checkPhone()) {
            //显示进度条
            mPbShowProgress.setVisibility(View.VISIBLE);
            mTvShowresult.setVisibility(View.INVISIBLE);
            mLlShowsearchresult.setVisibility(View.INVISIBLE);
            //对搜索按钮进行动态设置
            mTvSearch.setTextColor(CommonUtil.getColor(R.color.seach_text_disable));
            mTvSearch.setClickable(false);
            KeyBoardUtils.closeKeybord(this, mEtSearchnum);
            getCustomerInfo();
        }
    }


    /**
     * 获取Customer信息通过电话号码
     */
    private void getCustomerInfo() {
        String phoneNumOrName = mEtSearchnum.getText().toString().trim();
        if (isCustomerFragment) {
            // 本地搜索没有名字
            RequestCustomerTask.doRequestCustomerByPhone(this, phoneNumOrName, new HttpCallback<CustomerBean>() {
                @Override
                public void onSuccess(CustomerBean result) {
                    processResult(result);
                }

                @Override
                public void onFailParam(String info) {
                    onFailParamData();
                }
            });
        } else {
            //公海搜索存在姓名搜索
            RequestCustomerTask.doRequestCustomerInSeaByPhone(this, phoneNumOrName, isLoadMore ? datanum : 0, new HttpCallback<List<CustomerBean>>() {
                @Override
                public void onSuccess(List<CustomerBean> result) {
                    if (result.size() < 20) {
                        seaAdapter.setEnableLoadMore(false);
                    } else {
                        seaAdapter.setEnableLoadMore(true);
                    }
                    processInSeaResult(result);
                }

                @Override
                public void onFailParam(String info) {
                    if (seaAdapter.getData().size() == 0) {
                        onFailParamData();
                    } else {
                        seaAdapter.loadMoreEnd(true);
                    }
                }

                @Override
                public void onFail(String exception) {
                    super.onFail(exception);
                    onFailParamData();
                }
            });
        }
    }

    /**
     * 处理公海搜索结果
     * @param result
     */
    private void processInSeaResult(List<CustomerBean> result) {
        if (isLoadMore) {
            if (result.size() > 0) {
                seaAdapter.addData(result);
                seaAdapter.loadMoreComplete();
                isLoadMore = false;
            } else {
                seaAdapter.loadMoreFail();
            }
        } else {
            mCustomerInSealist.clear();
            mCustomerInSealist.addAll(result);
            seaAdapter.notifyDataSetChanged();
            //隐藏进度条
            mPbShowProgress.setVisibility(View.INVISIBLE);
            mRvShowsearch.setVisibility(View.VISIBLE);
            mLlShowsearchresult.setVisibility(View.INVISIBLE);
            mTvSearch.setTextColor(CommonUtil.getColor(R.color.seach_text_enable));
            mTvSearch.setClickable(true);
        }
    }

    /**
     * 请求参数错误的UI处理
     */
    private void onFailParamData() {
        mCustomerlist.clear();
        mPbShowProgress.setVisibility(View.INVISIBLE);
        mLlShowsearchresult.setVisibility(View.VISIBLE);
        mRvShowsearch.setVisibility(View.INVISIBLE);
        mTvSearch.setTextColor(CommonUtil.getColor(R.color.seach_text_enable));
        mTvSearch.setClickable(true);
    }

    /**
     * 对结果进行处理
     *
     * @param result
     */
    private void processResult(CustomerBean result) {
        mCustomerlist.clear();
        mCustomerlist.add(result);
        if (isCustomerFragment) {
            mAdapter.notifyDataSetChanged();
        } else {
            seaAdapter.notifyDataSetChanged();
        }
        //隐藏进度条
        mPbShowProgress.setVisibility(View.INVISIBLE);
        mRvShowsearch.setVisibility(View.VISIBLE);
        mLlShowsearchresult.setVisibility(View.INVISIBLE);
        mTvSearch.setTextColor(CommonUtil.getColor(R.color.seach_text_enable));
        mTvSearch.setClickable(true);
    }


    /**
     * 检查Phone
     *
     * @return
     */
    private boolean checkPhone() {
        String phone = mEtSearchnum.getText().toString().trim();
        //检查手机号是否为空
        if (TextUtils.isEmpty(phone)) {
            ToastUtil.showToast("手机号码不能为空！");
            return false;
        }
        return true;
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            searchCustomerByPhone();
        }
        return false;
    }

    @Override
    public void onLoadMoreRequested() {
        datanum = seaAdapter.getData().size();
        isLoadMore = true;
        getCustomerInfo();
    }
}
